import axios from 'axios';
import * as XLSX from "xlsx";
import {ref, reactive, computed, watch} from 'vue'
import {storeToRefs} from "pinia";
import {
    useGepCulturalServiceStore,
    useGepDataStore,
    useGepRegulationServiceStore,
    useGepSupplyServiceStore
} from "@/stores/gep";
import {addGepResult} from "api/services/gepService";
import {GepResult} from "api/types/gep";
import {ElMessage} from "element-plus";

const gepSupplyServiceStore = useGepSupplyServiceStore();
const gepRegulationServiceStore = useGepRegulationServiceStore();
const gepCulturalServiceStore = useGepCulturalServiceStore();
const gepDataStore = useGepDataStore();
export const {
    outGepSupplyService, outCalcMaterialSupply, outCalcWaterResources, outEcologicalEnergy,
    inLocalWaterPrice, inWaterResources, inEcologicalEnergy, inAnimalHusbandry, inForestry, inFishery, inAgricultural
} = storeToRefs(gepSupplyServiceStore);
export const {
    outGepCulturalService,
    outTourismHealth,
    outCalcLeisureRecreation,
    outCalcLandscapeAppreciation,
    inRoomPrice,
    inHotelRooms,
    inUrbanPopulation,
    inTourismRevenue,
    inDisposableIncome,
    inHousingAreaPerCapita,

} = storeToRefs(gepCulturalServiceStore);
export const {
    outGepRegulationService,

    outCalcNoiseReduced,
    outCalcBiodiversityProtection,

    inProtectedCost,
    inProtectedArea,
    inFloodRegulation,
    inAirPurification,
    inCarbonSequestration,
    inClimateRegulation,
    inNegativeOxygenIons,
    inOxygenRelease,
    inSoilConservation,
    inWaterPurification,
    inWaterSourceConservation
} = storeToRefs(gepRegulationServiceStore);
export const {
    gepTown,
    gepResultAreaOne,
    outGepResultArea,
    gepCity,
    gepDistrict,
    gepYear,
    gepValue,
    isSubmitted,
    count
} = storeToRefs(gepDataStore);


// 从环境变量中获取 BASE_URL
// const BASE_URL = import.meta.env.VUE_APP_API_URL;
// const BASE_URL_dev = 'http://localhost:8030';
const BASE_URL_pre = 'http://longbhu.cn:8033';
const BASE_URL = BASE_URL_pre;

export interface Region {
    id: number;
    region: string;
    region_en: string;
    data: Record<string, any>;  // 使用 Record 定义 JSON 数据
}

export let optionsRegionApi: Region[] = [];

// export const getOptionsRegion = async (): Promise<Region[]> => {
//     try {
//         const response = await axios.get<Region[]>(`${BASE_URL}/api/optionRegions`, {
//             params: {region_en: 'shangluo'},  // 将 region_en 作为查询参数
//         });
//         optionsRegionApi = response.data;
//         console.log("optionsRegionApi", optionsRegionApi);
//         return response.data;
//     } catch (error) {
//         console.error('Error fetching regions:', error);
//         throw error;  // 抛出错误以便调用者处理
//     }
// };


// gep输入数据的保存post与获取方法get

const message = ref('');

// export async function saveInputGEP() {
//     try {
//         // 定义要发送的数据
//         const data = {
//             gepCity: gepCity.value,
//             gepDistrict: gepDistrict.value,
//             gepTown: gepTown.value,
//             gepYear: gepYear.value,
//             inAgricultural: inAgricultural.value,
//             inAnimalHusbandry: inAnimalHusbandry.value,
//             inForestry: inForestry.value,
//             inFishery: inFishery.value,
//             inEcologicalEnergy: inEcologicalEnergy.value,
//             inWaterResources: inWaterResources.value,
//             inLocalWaterPrice: inLocalWaterPrice.value,
//
//             inRoomPrice: inRoomPrice.value,
//             inHotelRooms: inHotelRooms.value,
//             inUrbanPopulation: inUrbanPopulation.value,
//             inTourismRevenue: inTourismRevenue.value,
//             inDisposableIncome: inDisposableIncome.value,
//             inHousingAreaPerCapita: inHousingAreaPerCapita.value,
//
//
//
//             inProtectedCost: inProtectedCost.value,
//             inProtectedArea: inProtectedArea.value,
//
//
//         };
//         console.log("saveInputGEP要发送的数据：", data);
//
//         // 发送POST请求
//         const response = await axios.post(`${BASE_URL}/gepInputData`, data);
//
//         // 处理响应
//         if (response.status === 201) {
//             console.log(response.data.message);
//
//         } else if (response.status === 200) {
//             console.log(response.data.message);
//             // 这里可以添加一个方法来通知用户数据创建失败
//         } else {
//             console.log(response.data.message);
//         }
//         return response.status;
//     } catch (error) {
//         // 处理请求错误
//         console.error('Error submitting data:', error);
//         // 这里可以添加一个方法来通知用户请求错误
//     }
// }
//
//
// export async function getInputGEP(gepCity: any, gepDistrict: any, gepTown: any, gepYear: any) {
//     try {
//         // 定义查询参数
//         const params = {
//             gepCity: gepCity,
//             gepDistrict: gepDistrict,
//             gepTown: gepTown,
//             gepYear: gepYear,
//         };
//         // console.log('await-params', params);
//         // 发送GET请求
//
//         const response = await axios.get(`${BASE_URL}/gepInputData`, {params});
//
//         // 处理响应
//         if (response.status === 203) {
//             // 处理错误情况
//             // console.error(response.data.error);
//             console.log('该地区未保存过参数！');
//             gepDataStore.resetGEP();
//             // 这里可以添加一个方法来通知用户错误信息
//         } else if(response.status === 200) {
//             // 处理数据
//             // console.log('获取到该地区的GEP输入的数据如下:', response.data);
//             const data = response.data;
//             inAgricultural.value = data.inAgricultural || 0;
//             inAnimalHusbandry.value = data.inAnimalHusbandry || 0;
//             inForestry.value = data.inForestry || 0;
//             inFishery.value = data.inFishery || 0;
//             inEcologicalEnergy.value = data.inEcologicalEnergy || 0;
//             inWaterResources.value = data.inWaterResources || 0;
//             inLocalWaterPrice.value = data.inLocalWaterPrice || 0;
//             inProtectedArea.value = data.inProtectedArea || 0;
//             inProtectedCost.value = data.inProtectedCost || 0;
//             inReservoirCapacity.value = data.inReservoirCapacity || 0;
//             inReservoirCost.value = data.inReservoirCost || 0;
//             inHighwayMileage.value = data.inHighwayMileage || 0;
//             inHighwayGreeningDegree.value = data.inHighwayGreeningDegree || 0;
//             inTourismRevenue.value = data.inTourismRevenue || 0;
//             inDisposableIncome.value = data.inDisposableIncome || 0;
//             inGreenSpacePerCapita.value = data.inGreenSpacePerCapita || 0;
//             inUrbanPopulation.value = data.inUrbanPopulation || 0;
//             inHotelRooms.value = data.inHotelRooms || 0;
//             inRoomPrice.value = data.inRoomPrice || 0;
//             inHousingAreaPerCapita.value = data.inHousingAreaPerCapita || 0;
//
//             return response.data; // 返回数据供调用者使用
//         }
//         return response.status;
//     } catch (error) {
//         // 处理请求错误
//         // console.error('Error fetching data:', error);
//         console.log('response.data.error2');
//         // 这里可以添加一个方法来通知用户请求错误
//         throw error; // 抛出错误供调用者处理
//     }
// }

// gep计算结果的保存post与获取方法get与删除del


// 创建GEP结果记录
// export async function createGepResult() {
//     try {
//         const data = {
//             year: gepYear.value,
//             gepCity: gepCity.value,
//             gepDistrict: gepDistrict.value,
//             gepTown: gepTown.value,
//             gepResult: gepResult.value,
//             materialSupplyValue: materialSupplyValue.value,
//             cleanEnergyValue: cleanEnergyValue.value,
//             waterResourcesValue: waterResourcesValue.value,
//             tourismHealthValue: tourismHealthValue.value,
//             leisureRecreationValue: leisureRecreationValue.value,
//             landscapeAppreciationValue: landscapeAppreciationValue.value,
//         };
//         // console.log("创建gep结果的数据：", data)
//
//         // const response = await axios.post(`${BASE_URL}/gepResult`, data);
//         const response = await addGepResult( <GepResult>data);
//         // console.log("响应的结果的数据：", response)
//         // console.log("响应的结果的数据状态码：", response.status)
//         // console.log("响应的结果的数据错误：", response.data.error)
//
//         if (response.status === 201) {
//             console.log('GEP Result created successfully', response.data);
//             ElMessage.success('新增成功');
//             // 这里可以添加一个方法来通知用户创建成功
//         } else if (response.status === 400) {
//             console.log('有已经计算过的gep结果，执行更新函数', response.data);
//             // await updateGepResult();
//         } else {
//             console.log('Failed to create GEP Result Record with the same year and gepResultArea already exists', response.data.error);
//             // 这里可以添加一个方法来通知用户创建失败
//         }
//         return response.status;
//     } catch (error) {
//         console.error('Error creating GEP Result:', error);
//         // 这里可以添加一个方法来通知用户请求错误
//     }
// }

// 获取GEP结果记录
// export async function getGepResult() {
//     try {
//         const params = {
//             year: gepYear.value,
//             gepResultArea: gepResultAreaOne.value
//         };
//
//         const response = await axios.get(`${BASE_URL}/gepResult`, {params});
//         if (response.status === 200) {
//             console.log('GEP Result retrieved successfully', response.data);
//             // 这里可以添加一个方法来处理获取到的数据
//         } else {
//             console.error('Failed to retrieve GEP Result', response.data.error);
//             // 这里可以添加一个方法来通知用户获取失败
//         }
//         return response.status;
//     } catch (error) {
//         console.error('Error retrieving GEP Result:', error);
//         // 这里可以添加一个方法来通知用户请求错误
//     }
// }

// 更新GEP结果记录
// export async function updateGepResult() {
//     try {
//         const data = {
//             year: gepYear.value,
//             gepResultArea: gepResultAreaOne.value,
//             gepResult: gepValue.value,
//
//         };
//
//         const response = await axios.put(`${BASE_URL}/gepResult`, data);
//         if (response.status === 200) {
//             console.log('GEP Result updated successfully', response.data);
//             // 这里可以添加一个方法来通知用户更新成功
//         } else if (response.status === 400) {
//             console.log('更新参数异常', response.data);
//         } else {
//             console.error('Failed to update GEP Result', response.data.error);
//             // 这里可以添加一个方法来通知用户更新失败
//         }
//         return response.status;
//     } catch (error) {
//         console.error('Error updating GEP Result:', error);
//         // 这里可以添加一个方法来通知用户请求错误
//     }
// }
//
// // 删除GEP结果记录
// export async function deleteGepResult() {
//     try {
//         const params = {
//             year: gepYear.value,
//             gepResultArea: gepResultAreaOne.value
//         };
//
//         const response = await axios.delete(`${BASE_URL}/gepResult`, {params});
//         if (response.status === 200) {
//             console.log('GEP Result deleted successfully', response.data.message);
//             // 这里可以添加一个方法来通知用户删除成功
//         } else {
//             console.error('Failed to delete GEP Result', response.data.error);
//             // 这里可以添加一个方法来通知用户删除失败
//         }
//         return response.status;
//     } catch (error) {
//         console.error('Error deleting GEP Result:', error);
//         // 这里可以添加一个方法来通知用户请求错误
//     }
// }

export async function selectGepResult(year:number) {

    try {
        const response = await axios.get(`${BASE_URL}/gepResultAll`, {
            params: {
                year: year,
                // gepResultArea: gepResultArea
            }
        });

        if (response.status === 200) {
            const data = response.data;
            if (data) {
                console.log('selectGepResult的data', data)
                return data; // 返回 GEP 结果
            } else {
                console.log(`No GEP result found .`);
                return null;
            }
        } else {
            console.error(`Error: Received status code ${response.status}`);
        }
    } catch (error) {
        // console.error('Error fetching GEP result:', error.response ? error.response.data : error.message);
        return null; // 在捕获错误时返回 null
    }
}




// 下载表格
export const exportToExcel = () => {
    // 数据定义
    // console.log("excelName",excelName.value)
    const data = [
        ['', '项目（万元）', outGepResultArea.value],
        ['物质价值', '生态物质产品', outCalcMaterialSupply.value],
        ['物质价值', '清洁能源', outEcologicalEnergy.value],
        ['物质价值', '水资源', outCalcWaterResources.value],
        ['调节服务价值', '水源涵养', inWaterSourceConservation.value],
        ['调节服务价值', '土壤保持', inSoilConservation.value],
        ['调节服务价值', '洪水调蓄', inFloodRegulation.value],
        ['调节服务价值', '空气净化', inAirPurification.value],
        ['调节服务价值', '水质净化', inWaterPurification.value],
        ['调节服务价值', '固碳价值', inCarbonSequestration.value],
        ['调节服务价值', '释氧价值', inOxygenRelease.value],
        ['调节服务价值', '气候调节', inClimateRegulation.value],
        ['调节服务价值', '负氧离子', inNegativeOxygenIons.value],
        ['调节服务价值', '生物多样性保护', outCalcBiodiversityProtection.value],
        ['调节服务价值', '噪音消减', outCalcNoiseReduced.value],
        ['文旅价值', '旅游康养', outTourismHealth.value],
        ['文旅价值', '休闲游憩', outCalcLeisureRecreation.value],
        ['文旅价值', '景观增值', outCalcLandscapeAppreciation.value],
    ];

    // 创建工作表
    const ws = XLSX.utils.aoa_to_sheet(data);

    // 设置合并单元格
    ws['!merges'] = [
        {s: {r: 1, c: 0}, e: {r: 3, c: 0}},
        {s: {r: 4, c: 0}, e: {r: 14, c: 0}},
        {s: {r: 15, c: 0}, e: {r: 17, c: 0}}
    ];

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    // 导出文件
    const xlsxName = outGepResultArea.value + "-GEP计算结果.xlsx"
    XLSX.writeFile(wb, xlsxName);
};


// 暂时无用的函数

// function formatGepValue(value) {
//     // 将值转换为数字，确保处理正确
//     const numericValue = parseFloat(value);
//
//     // 检查整数位数
//     if (numericValue >= 10000) { // 6位数的界限
//         return (numericValue / 10000).toFixed(2) + " 亿元";
//     } else {
//         return numericValue.toFixed(2) + " 万元";
//     }
// }

// 获取当前日期
const currentDate = new Date();

// 格式化日期
const formattedDate = computed(() => {
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
    const day = String(currentDate.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
});